package com.yyk.yykywd.mvvm.ui

import android.os.Handler
import android.os.Message
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.google.gson.Gson
import com.yyk.yykywd.*
import com.yyk.yykywd.bean.BaseBean
import com.yyk.yykywd.mvvm.adapter.AddMaterialAdapter
import com.yyk.yykywd.mvvm.base.BaseTakePhotoActivity
import com.yyk.yykywd.mvvm.entity.UploadBean
import com.yyk.yykywd.mvvm.event.FinishWorkDetail
import com.yyk.yykywd.mvvm.view_model.AddPictureViewModel
import com.yyk.yykywd.mvvm.view_model.WorkDetailViewModel
import com.yyk.yykywd.util.DensityUtils
import com.yyk.yykywd.util.ToastUtil
import com.yyk.yykywd.widght.SpaceItemDecoration
import kotlinx.android.synthetic.main.activity_add_return_money.*
import kotlinx.android.synthetic.main.rl_bottom.*
import org.devio.takephoto.model.TResult
import org.greenrobot.eventbus.EventBus

class AddReturnMoneyActivity : BaseTakePhotoActivity() {
    private lateinit var viewModel: AddPictureViewModel
    private lateinit var workDetailViewModel: WorkDetailViewModel
    private lateinit var adapter: AddMaterialAdapter

    private val handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val result = msg.obj as String
            val gson = Gson()
            val info: UploadBean = gson.fromJson(result, UploadBean::class.java)
            if (info.code != 1) {
                ToastUtil.showShort(mActivity, info.msg)
                return
            }

            viewModel.receipt.add(info.data)
            adapter.notifyDataSetChanged()
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_add_return_money
    }

    override fun initView() {
        viewModel = getViewModel(this, AddPictureViewModel::class.java)
        workDetailViewModel = getViewModel(this, WorkDetailViewModel::class.java)
        with(workDetailViewModel) {
            id = intent.getStringExtra(ID)
            pact_id = intent.getStringExtra(PACT_ID)
            position = intent.getIntExtra(POSITION, 0)
        }
        setBackArrow {
            backAndDelImg()
        }
        setTitle("添加回款")
        rv_receipt.layoutManager = GridLayoutManager(mActivity, 3)
        rv_receipt.addItemDecoration(SpaceItemDecoration(DensityUtils.dp2px(mActivity, 10f)))
        adapter = AddMaterialAdapter(mActivity, viewModel.receipt)
        adapter.maxImages = AddMaterialActivity.MAX_IMAGES
        rv_receipt.adapter = adapter
    }

    override fun takeSuccess(result: TResult) {
        viewModel.uploadContractImg(CONTRACT, result.image.compressPath)
    }

    override fun initData() {
        workDetailViewModel.getAgentDetail()
    }

    override fun setListener() {
        super.setListener()
        tv_execute.setOnClickListener {
            if (required()) {
                return@setOnClickListener
            }
            val s = getTextString(et_return_money)
            val situation = getTextString(et_hospital_situation)
            if (workDetailViewModel.equalAgencyPrice(s.toInt())
                    && viewModel.back_money_num == 1) {
                //合同类型为定金合同且合同被补全过
                if (viewModel.flag == 2 && viewModel.transition == 1) {
                    show(mActivity, "是否确认保存回款信息",
                            "保存后本次业务回款完成，您可在\"全款合同列表\"中查看此项业务",
                            "确认",
                            "取消") {
                        workDetailViewModel.backMoney(s, viewModel.receipt, situation)
                    }
                } else {
                    //合同类型为全款合同
                    if (viewModel.flag == 1) {
                        show(mActivity, "是否确认保存回款信息",
                                "保存后本次业务回款完成，您可在\"全款合同列表\"中查看此项业务",
                                "确认",
                                "取消") {
                            workDetailViewModel.backMoney(s, viewModel.receipt, situation)
                        }
                    } else {
                        show(mActivity, "",
                                "是否确认保存回款信息",
                                "确认",
                                "取消") {
                            workDetailViewModel.backMoney(s, viewModel.receipt, situation)
                        }
                    }
                }

            } else {
                show(mActivity, "",
                        "是否确认保存回款信息",
                        "确认",
                        "取消") {
                    workDetailViewModel.backMoney(s, viewModel.receipt, situation)
                }
            }

        }

        workDetailViewModel.agentDetail1.observe(this, Observer {
            it.info[workDetailViewModel.position]?.run {
                tv_agent_site_name.text = "代理站点名称：" + agency_name
                tv_agent_site_type.text = "代理站点类型：" + status
                tv_agent_price.text = "代理价格：" + agency_money
                if (info1.flag == 1) {
                    tv_contract_type.text = "合同类型：全款合同"
                } else {
                    tv_contract_type.text = "合同类型：定金合同"
                }
                if (dj_money > 0) {
                    tv_deposit_amount.visibility = View.VISIBLE
                    tv_deposit_amount.text = "定金金额：" + dj_money + "元"
                } else {
                    tv_deposit_amount.visibility = View.GONE
                }
                tv_amount_received.text = "已回款金额：" + already_money + "元"
                tv_still_need.text = "仍需回款金额：" + rxhk_money + "元"

                workDetailViewModel.stillNeedMoney = rxhk_money
                workDetailViewModel.alreadyMoney = already_money

                viewModel.flag = info1.flag
                viewModel.transition = transition ?: 0
            }
            it.data?.run {
                viewModel.back_money_num = back_money_num
            }

        })

        workDetailViewModel.base.observe(this, Observer {
            ToastUtil.showShort(it.msg)
            if (it.code == 200) {
                val s = getTextString(et_return_money)
                if (workDetailViewModel.equalAgencyPrice(s.toInt())
                        && viewModel.back_money_num == 1) {
                    //合同类型为定金合同且合同被补全过
                    if (viewModel.flag == 2 && viewModel.transition == 1) {
                        EventBus.getDefault().post(FinishWorkDetail())
                    }
                    //合同类型为全款合同
                    if (viewModel.flag == 1) {
                        EventBus.getDefault().post(FinishWorkDetail())
                    }
                }
                finish()
            }
        })

        viewModel.responseMessage.observe(this, Observer<String> { t ->
            val msg = Message.obtain()
            msg.what = 1
            msg.obj = t
            handler.sendMessage(msg)
        })

        viewModel.delSuccess.observe(this, Observer<BaseBean> {
            if (it.code != 200) {
                ToastUtil.showShort(it.msg)
                return@Observer
            }
            if (viewModel.delSingleOrMulti == MULTI) {
                finish()
                return@Observer
            }
            viewModel.receipt.removeAt(viewModel.del_position)
            adapter.notifyDataSetChanged()
        })

        et_return_money.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (!s.isNullOrBlank()) {
                    val overAgencyPrice = workDetailViewModel.overAgencyPrice(s.toString().toInt())
                    if (overAgencyPrice) {
                        tv_over.visibility = View.VISIBLE
                    } else {
                        tv_over.visibility = View.GONE
                    }
                } else {
                    tv_over.visibility = View.GONE
                }
            }
        })

        setAdapterChildClickListener(mActivity, adapter,
                getTakePhoto(),
                1, object : UploadClickListener {
            override fun clickIv() {

            }

            override fun clickRemove(position: Int) {
                viewModel.del_position = position
                viewModel.delSingleOrMulti = SINGLE
                viewModel.removeImg(viewModel.receipt[position])
            }

        })
    }

    private fun required(): Boolean {
        val s = getTextString(et_return_money)
        if (s.isEmpty()) {
            ToastUtil.showShort("请填写回款金额")
            return true
        }
        if (workDetailViewModel.overAgencyPrice(s.toInt())) {
            ToastUtil.showShort("回款金额已超过代理价格")
            return true
        }
        if (viewModel.receipt.isEmpty()) {
            ToastUtil.showShort("请上传收据照片")
            return true
        }
        return false
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            backAndDelImg()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun backAndDelImg() {
        with(viewModel) {
            val list = receipt
            if (list.isNotEmpty()) {
                delSingleOrMulti = MULTI
                removeImg(listToString(list))
            } else {
                finish()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
    }
}
